package com.tz.login;  

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tz.system.menu.MenuUtils;
import com.tz.system.user.UserUtils;
import com.tz.system.user.model.UserInfo;


@Controller
@RequestMapping( "/system/user/login")
public class UserLoginController {
	
	@Autowired
	private MenuUtils menuUtils;
	
	@RequestMapping(value = "/getLogin")
	public String checkLogin(HttpServletRequest request,Model model) {
		String userName = request.getParameter("username");
		String passWord = request.getParameter("password");
		if(UserUtils.checkUserPwdValid(userName, passWord)){
			//将用户放入session中
			UserUtils.setSessionUser(request, userName);
			return "redirect:/system/user/login/main.do";
		}
		return "redirect:/system/user/login/error.do";
	}
	
	/**
	 * 登录失败
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/error")
	public String selectPage(HttpServletRequest request, Model model) {
		model.addAttribute("msg", "用户名或者密码错误！");
		return "forward:/login/login.jsp";
	}
  
	/**
	 * 登录成功
	 * @param loginUser
	 * @param randomCode
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/main")
	public String login(HttpServletRequest request, Model model) {
		// 菜单列表需要展现出来
		String trees = menuUtils.makeMenusTree(request);
		model.addAttribute("trees", trees);
		UserInfo userInfo = UserUtils.getSessionUser(request);
		model.addAttribute("userInfo", userInfo);
		return "/frame/index";
	}
	
	/**
	 * 用户登出操作
	 * @param HttpServletRequest request
	 * @param Model model
	 * @return String 返回url
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession();
		// 注销session
		session.invalidate();
		return "forward:/login/login.jsp";
	}
  
  
}
